package itu.twitterandro.application;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;

public class TwitterAndroActivity extends Activity {
	static final String TAG = "UpdaterService";

	public Bitmap placeholder;
	public String screenName;
	private Twitter t;
	private Intent intent;
	Twitter twitter;

	private Handler handler;

	private ServiceConnection serviceConnection = new ServiceConnection() {

		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i(TAG, "Service connection established");

			// that's how we get the client side of the IPC connection
			api = TweetCollectorApi.Stub.asInterface(service);
			try {
				api.addListener(collectorListener);
			} catch (RemoteException e) {
				Log.e(TAG, "Failed to add listener", e);
			}

			updateTweetView();
		}

		public void onServiceDisconnected(ComponentName name) {
			Log.i(TAG, "Service connection closed");
		}
	};

	private TweetCollectorApi api;

	private TweetCollectorListener.Stub collectorListener = new TweetCollectorListener.Stub() {

		public void handleTweetsUpdated() throws RemoteException {
			updateTweetView();
		}
	};

	private void updateTweetView() {
		// doing this in a Handler allows to call this method safely from any
		// thread
		// see Handler docs for more info
		handler.post(new Runnable() {

			public void run() {
				ArrayList<Tweet> tweets = getTweets(t);
				ListView listView = (ListView) findViewById(R.id.ListViewId);
				listView.setAdapter(new TweetItemAdapter(
						TwitterAndroActivity.this, R.layout.listitem, tweets));
			}
		});
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		handler = new Handler();

		t = ((TwitterApplication) getApplication()).getTwitter();

		ArrayList<Tweet> tweets = getTweets(t);
		ListView listView = (ListView) findViewById(R.id.ListViewId);
		listView.setAdapter(new TweetItemAdapter(this, R.layout.listitem,
				tweets));

		intent = new Intent(TweetCollectorService.class.getName());

		startService(intent);

		bindService(intent, serviceConnection, 0);

		Log.i(TAG, "Activity created");
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_new_message:
			newTweet();
			return true;
		case R.id.menu_search:
			searchTweets();
			return true;
		case R.id.menu_logout:
			logout();
			return true;
		}
		return false;
	}

	public void searchTweets() {
		Intent launchSearchIntent = new Intent(TwitterAndroActivity.this,
				SearchTweetsActivity.class);
		startActivity(launchSearchIntent);
	}

	public void logout() {
		twitter = new TwitterFactory().getInstance();
		SharedPreferences settings = getSharedPreferences(
				TwitterKeys.PREFS_NAME, MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.remove("accessTokenToken");
		editor.remove("accessTokenSecret");
		editor.commit();
		twitter.setOAuthConsumer(null, null);

		intent = new Intent(TweetCollectorService.class.getName());
		stopService(intent);

		intent = new Intent(this, AuthActivity.class)
				.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

		startActivity(intent);
	}

	public void newTweet() {
		Intent launchNewIntent = new Intent(TwitterAndroActivity.this,
				UpdateStatusActivity.class);
		startActivity(launchNewIntent);

	}

	private static ArrayList<JSONObject> convertTimelineToJson(
			List<Status> statuses) {
		ArrayList<JSONObject> JOBS = new ArrayList<JSONObject>();
		try {
			if (statuses.size() > 0) {
				for (Status s : statuses) {
					String avatar = "http://"
							+ s.getUser().getProfileImageURL().getHost()
							+ s.getUser().getProfileImageURL().getPath();
					JSONObject object = new JSONObject();
					object.put("text", s.getText());
					String timePosted = Utility.getDateDifference(s
							.getCreatedAt());
					object.put("tweetDate", timePosted);
					object.put("from_user", s.getUser().getName());
					object.put("profile_image_url", avatar);
					// object.put("userObj", s.getUser());
					// object.put("tweetId", s.getId());

					JOBS.add(object);
				}
			} else {
				JSONObject object = new JSONObject();
				object.put("tweet",
						"You have not logged in yet! Please log on to view latest tweets");
				object.put("author", "");
				JOBS.add(object);
			}

		} catch (JSONException e1) {
			Log.e("JSON", "There was an error creating the JSONObject", e1);
		}
		return JOBS;
	}

	public ArrayList<Tweet> getTweets(Twitter twitter) {

		List<Status> statuses = new ArrayList<Status>();

		try {
			Paging p = new Paging(1); // get first page only of timeline - dont
										// want to return everything!
			statuses = twitter.getHomeTimeline(p);
		} catch (TwitterException e) {
			Log.e("Twitter", "Error retrieving tweets");
			Log.e("Twitter", e.getMessage());
		}

		ArrayList<Tweet> tweets = new ArrayList<Tweet>();

		ArrayList<JSONObject> jsonObjectList = convertTimelineToJson(statuses);

		try {
			for (JSONObject t : jsonObjectList) {
				Tweet tweet = new Tweet(t.get("from_user").toString(), t.get(
						"text").toString(), t.get("profile_image_url")
						.toString(), t.get("tweetDate").toString());

				tweets.add(tweet);
			}
		} catch (JSONException e) {
		}

		return tweets;
	}
	
}